#pragma once

#include <sys/types.h>       
#include <sys/socket.h>
#include <unistd.h>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>

enum
{
    SOCKETERR = 2,
    BINDERR,
    LISTENERR
};

const std::string serverip = "0.0.0.0";

class Sock
{
public:
    Sock() : _sockfd(0)
    { }
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "socket fail, error num:" << errno << ", errstring:" << strerror(errno) << std::endl;
            exit(SOCKETERR);
        }
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        if(bind(_sockfd, (struct sockaddr*)&server, sizeof(server)) < 0)
        {
            std::cout << "bind fail, error num:" << errno << ", errstring:" << strerror(errno) << std::endl;
            exit(BINDERR);
        }
    }
    void Listen()
    {
        if(listen(_sockfd, 10) < 0)
        {
            std::cout << "listen fail, error num:" << errno << ", errstring:" << strerror(errno) << std::endl;
            exit(LISTENERR);
        }
    }
    int Accept(std::string& ip, uint16_t& port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int ret = accept(_sockfd, (struct sockaddr*)&client, &len);
        if(ret < 0)
        {
            std::cout << "accpet fail, error num:" << errno << ", errstring:" << strerror(errno) << std::endl;
            return -1;
        }
        ip = inet_ntoa(client.sin_addr);
        port = ntohs(client.sin_port);
        return ret;
    }
    ~Sock()
    { 
        close(_sockfd);
    }
private:
    int _sockfd;
};